package cn.tedu.serviceEdu.service.impl;

import cn.tedu.serviceBase.exception.EducationException;
import cn.tedu.serviceEdu.entity.EduChapter;
import cn.tedu.serviceEdu.entity.EduSubject;
import cn.tedu.serviceEdu.entity.EduVideo;
import cn.tedu.serviceEdu.mapper.EduChapterMapper;
import cn.tedu.serviceEdu.service.EduChapterService;
import cn.tedu.serviceEdu.service.EduVideoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.xml.internal.bind.v2.TODO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author hong
 * @since 2023-05-18
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {
    @Autowired
    private EduVideoService videoService;

    @Override
    public List<EduChapter> getChapterList(String courseId) {
        if (courseId.isEmpty()) {
            throw new EducationException(20001, "课程不存在");
        }
        LambdaQueryWrapper<EduChapter> lqw = new LambdaQueryWrapper<>();
        lqw.eq(EduChapter::getCourseId, courseId);
        lqw.orderByAsc(EduChapter::getCreateTime);
        List<EduChapter> chapterList = this.list(lqw);

        LambdaQueryWrapper<EduVideo> lqwVideo = new LambdaQueryWrapper<>();
        lqwVideo.eq(EduVideo::getCourseId, courseId);
        lqwVideo.orderByAsc( EduVideo::getCreateTime);
        List<EduVideo> videoList = videoService.list(lqwVideo);

        for (int i = 0; i < chapterList.size(); i++) {
            EduChapter chapter = chapterList.get(i);
            List<EduVideo> videoListByChapter = new ArrayList<>();
            for (int j = 0; j < videoList.size(); j++) {
                EduVideo video = videoList.get(j);
                if (chapter.getId().equals(video.getChapterId())){
                    videoListByChapter.add(video);
                    chapter.setChildren(videoListByChapter);
                }
            }
        }
        return chapterList;
    }

    @Override
    public boolean removeByCourseId(String id) {
        QueryWrapper<EduChapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", id);
        Integer count = baseMapper.delete(queryWrapper);
        return null != count && count > 0;
    }

    @Override
    public List<EduChapter> nestedList(String courseId) {
        return null;
    }

}
